package cn.itcast.web.aspect;

import cn.itcast.domain.system.SysLog;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.SysLogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

import java.util.Date;

@Aspect
@Component
public class LogAspect {
    @Autowired
    private SysLogService sysLogService;

    @Autowired
    private HttpServletRequest request;

    @Around("bean(*Controller)")
    public Object isertLog(ProceedingJoinPoint pjp) {
        try {
            //执行被代理类的方法
            Object retV = pjp.proceed();

            //自动记录日志(封装日记类)
            SysLog sysLog = new SysLog();

            sysLog.setIp(request.getRemoteAddr());
            sysLog.setTime(new Date());
            sysLog.setMethod(pjp.getSignature().getName());
            sysLog.setAction(pjp.getTarget().getClass().getName());

            User loginInfo = (User) request.getSession().getAttribute("loginInfo");

            if (loginInfo != null) {
                sysLog.setUserName(loginInfo.getUserName());
                sysLog.setCompanyId(loginInfo.getCompanyId());
                sysLog.setCompanyName(loginInfo.getCompanyName());
            }

            //调用日志业务层保存日记信息到数据库
            sysLogService.save(sysLog);

            //返回方法的返回值
            return retV;

        } catch (Throwable throwable) {
            throw new RuntimeException(throwable);
        }
    }
}
